const { getDayStr } = require('./common')
const mapStatus = {
  '0': 'keep',
  '1': 'sale',
  '-1': 'patch'
}
Parse.Cloud.define('checkRoTask', async (req, res) => {
  try {
    const { ids, payload: {status} } = req.params
    const roTasks = await new Parse.Query('RoTask').containedIn('objectId', ids).limit(100000).find()
    const tasks = []
    const count = {

    }
    roTasks.forEach((item) => {
      const time = item.get('endTime')
      if (time) {
        const preStatus = item.get('status')
        const day = getDayStr(time)
        const current = count[day] || (count[day] = {
          keep: 0,
          sale: 0,
          patch: 0
        })
        if (status !== preStatus) {
          item.set('status', status)
          tasks.push(item)
          if (typeof preStatus === 'undefined') {
            current[mapStatus[status]]++
          } else {
            current[mapStatus[preStatus]]--
            current[mapStatus[status]]++
          }
        }
      }
    })

    const incomes = await Promise.all(Object.keys(count).map(day => new Parse.Query('RoIncome')
      .equalTo('incomeDay', day)
      .first()
      .then((result) => {
        const income = result || new Parse.Object('RoIncome', {
          'incomeDay': day
        })
        const current = count[day]
        Object.keys(current).forEach(key => income.increment(key, current[key]))
        return income
      })
    ))
    tasks.push(...incomes)
    await Parse.Object.saveAll(tasks)
    res.success('ok')
  } catch (err) {
    res.error(err)
  }
})

